package com.manager.common.job;

import com.manager.common.ssh.RemoteExecuteLinuxCommandTools;
import com.manager.common.utils.DataTools;
import com.manager.model.DockerContainerStats;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class IntervalGetDockerContainerInfo {

    @Value("${linux.ssh.ip}")
    private String ip;

    @Value("${linux.ssh.port}")
    private Integer port;

    @Value("${linux.ssh.password}")
    private String password;

    @Value("${linux.ssh.user.name}")
    private String userName;

    @Scheduled(fixedDelay = 10000)
    public void execute(){
        String command = " docker stats --no-stream | awk 'NR>1 {print $1,$2, $3,$4,$6,$7,$8,$10,$11,$13,$14}' ";
        List<String> out = new ArrayList<>();
        boolean hasSuccess = RemoteExecuteLinuxCommandTools.excuteRemoteSSH(ip,userName,password,port,out,command);
        if(!hasSuccess){
            return;
        }
        List<DockerContainerStats> realTimeStats = new ArrayList<>();
        out.forEach(v -> {
            String[] arr = v.split(" ");
            DockerContainerStats dockerContainerStats = new DockerContainerStats(arr[0],arr[1],arr[2],arr[3],arr[4],
                    arr[5],arr[6],arr[7],arr[8],arr[9],arr[10]);
            realTimeStats.add(dockerContainerStats);
        });
        DataTools.addAll(realTimeStats);
    }
}
